package siga.banco;

import java.sql.*;
import siga.pacotao.alertasSistema;
import siga.visao.index;
import siga.visao.verErros;

public class conexao {
    public static Connection banco = null;
    public static Statement stm = null;
    public static ResultSet rs = null;
    public static PreparedStatement ps = null;
    public static String AutoIncRS;

    public static void main (String args[]){ }

    public static void Conexao(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            banco = DriverManager.getConnection(index.bd,index.usbd,index.snbd);
            stm = banco.createStatement();
        } catch (ClassNotFoundException ex) {
            alertasSistema.alertaErro("(Conexao):\n"+ex.getMessage());
        }catch(SQLException ex){
            alertasSistema.alertaErro("(Conexao):\n"+ex.getMessage());
        }
    }

    public static void FechaConexao(){
        try{
            if(banco.isClosed()){
              banco.close();
            }
        }catch(SQLException ex){
            alertasSistema.alertaErro("(FechaConexao):\n"+ex.getMessage());
        }
    }

    public static void Query(String sql){
        try {
            rs = stm.executeQuery(sql);
        } catch (SQLException ex) {
            verErros.setErro("(Query): "+ex.getMessage());
        }
    }

    public static ResultSet res(){
        return rs;
    }
    public static void Inserir(String sql){
        try {
            stm.executeUpdate(sql);
        } catch (SQLException ex) {
            verErros.setErro("(Inserir): "+ex.getMessage());
        }
    }
    public static void AutoIncrementa(String tabela){
        try {
            rs = stm.executeQuery("select max(codigo) as novocodigo from " + tabela + " where cod_emp=" + index.cod_emp);
            rs.next();
            AutoIncRS = ""+(rs.getInt("novocodigo") + 1);
            stm.executeUpdate("insert into " + tabela + "(codigo,cod_emp) values(" + AutoIncRS + "," + index.cod_emp + ")");            
        } catch (SQLException ex) {
            verErros.setErro("(AutoIncrementa): "+ex.getMessage());
        }
    }

    public static void RemoveAutoIncrementa(String tabela){
        if(AutoIncRS != null){
            try {
                stm.executeUpdate("delete from " + tabela + " where codigo=" + AutoIncRS + " and cod_emp=" + index.cod_emp + "");
                AutoIncRS=null;
            } catch (SQLException ex) {
                verErros.setErro("(RemoveAutoIncrementa): "+ex.getMessage());
            }
        }
    }

}